<template>
  <div>
    <div class="event-select task-flex task-ai">
      <!-- 工单类型 -->
      <div class="task-flex task-ai task-mr24">
        <span>{{$t('common.label.taskTemplate')}}：</span>
        <el-select v-model="department" multiple clearable :placeholder="$t('report.taskSelect.placeholder1')" class="task-span1" @change="searchChange('taskType')" @clear="Params">
          <el-option
            v-for="item in departmentList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <!-- 完成时间 -->
      <div class="task-flex task-ai" v-if="reportType === 'task_success'">
        <span>{{$t('common.task.flow.finishTime')}}：</span>
        <el-date-picker
          class="task-span1"
          v-model="dataTime"
          type="datetimerange"
          :picker-options="pickerOptions"
          :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          align="right"
          value-format="timestamp"
          :default-time="['00:00:00', '23:59:59']"
          @change="searchChange('time')">
        </el-date-picker>
      </div>
      <!-- 人员 -->
      <div class="task-flex task-ai" v-else>
        <span>{{ $t('common.base.person')}}：</span>
        <el-select 
          v-model="personnel"
          clearable 
          multiple 
          collapse-tags 
          :placeholder="$t('common.placeholder.selectMember')" 
          class="task-span1" 
          @change="searchChange('user')" 
          @clear="Params"
          filterable
          remote
          :remote-method="remoteMethod"
          v-el-select-loadmore="loadmoreOptions"
        >
          <el-option
            v-for="(item, index) in personnelList"
            :key="index"
            :label="item.displayName"
            :origin="item"
            :value="item.userId"
          >
            <template v-if="isOpenData">
              <open-data type='userName' :openid="item.staffId"></open-data>
            </template>
          </el-option>
          
          <template slot="multiple" slot-scope="{ item }">
            <template v-if="isOpenData">
              <open-data type="userName" :openid="item.staffId"></open-data>
            </template>
            <template v-else>
              {{ item.displayName || item.name}}
            </template>
          </template>

        </el-select>
      </div>
    </div>

    <div class="event-select task-flex task-ai task-mt12">
      <!-- 团队 -->
      <div class="task-flex task-ai task-mr24">
        <span>{{$t('common.base.team')}}：</span>
        <biz-team-select :value="tagId" is-auto-select-child multiple collapse class="task-span1" :fetch-func="fetchTeam" @input="teamSelect" @remove="clearTeam" />
      </div>
      <!-- 人员 -->
      <div class="task-flex task-ai" v-if="reportType === 'task_success'">
        <span>{{$t('common.base.person')}}：</span>
        <el-select 
          v-model="personnel" 
          clearable 
          multiple 
          collapse-tags
          :placeholder="$t('common.placeholder.selectMember')" 
          class="task-span1" 
          @change="searchChange('user')" 
          @clear="Params"
          filterable
          remote
          :remote-method="remoteMethod"
          v-el-select-loadmore="loadmoreOptions"
        >
          <el-option
            v-for="(item, index) in personnelList"
            :key="index"
            :label="item.displayName"
            :value="item.userId"
            :origin="item"
          >
            <template v-if="isOpenData">
              <open-data type='userName' :openid="item.staffId"></open-data>
            </template>
          </el-option>
          
          <template slot="multiple" slot-scope="{ item }">
            <template v-if="isOpenData">
              <open-data type="userName" :openid="item.staffId"></open-data>
            </template>
            <template v-else>
              {{ item.displayName || item.name}}
            </template>
          </template>

        </el-select>
      </div>
    </div>
  </div>
</template>
<script>
// API
import * as ReportApi from '@src/api/ReportApi.ts';

import { nearDateBy, dayTimeEnd, useDatePicker } from 'pub-bbx-utils';
import { t } from '@src/locales'
import { isOpenData } from '@src/util/platform'
import { safeNewDate } from '@src/util/time';

const datePicker = useDatePicker()

export default {
  name: 'task-select',
  props: {
    reportType: {
      type: String
    }
  },
  data() {
    const startTime = +nearDateBy(1, 'week');
    const endTime = +dayTimeEnd();

    return {
      isOpenData,
      dataTime: [startTime, endTime],
      pickerOptions: {
        shortcuts: [
          datePicker.today(t('common.time.today')),
          datePicker.yesterday(t('common.time.yesterday')),
          datePicker.nearDate(t('common.time.lastWeek'), 1, 'week'),
          datePicker.nearDate(t('common.time.lastMonth'), 1, 'month'),
          datePicker.nearDate(t('common.time.lastThreeMonth'), 3, 'month'),  
        ]
      }, // 完成时间
      department: [], // 工单类型
      tagId: [], // 团队id
      tagList: [], // 团队列表
      departmentList: [], // 工单类型列表
      personnel: [], // 人员
      personnelList: [], // 人员列表
      total: 0, // 人员总数
      personSearchInfo: {
        userName: '',
        pageNum: 1, // 第几页
      },
      loadmoreOptions: { // 分页配置
        disabled: false,
        callback: this.loadmore,
        distance: 10
      }
    }
  },
  mounted() {
    this.taskTypes()
    this.teamUser()
    this.Params()
  },
  methods: {
    // S 团队筛选
    teamSelect(v) {
      this.tagId = v
      this.Params()
      this.personnel = [];
      this.remoteMethod();

      this.reportType && this.$track.commonFn.chartTrack(this.reportType, 'REPORT_SEARCH_TEAM', this.$track)
    },
    // 删除
    clearTeam() {
      this.personnel = [];
      this.remoteMethod();
    },
    fetchTeam(params){
      return this.$http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    // E 团队筛选
    // 工单类型
    async taskTypes() {
      this.departmentList = []
      const {succ, data} = await ReportApi.taskType()
      if (succ) {
        for(let key in data) {
          this.departmentList.push({
            value: key,
            label: data[key]
          })
        }
      }
    },
    // 人员数据
    async teamUser() {
      try {
        // this.personnel = []
        const { pageNum, userName } = this.personSearchInfo;
        const params = {
          queryAll: true,
          teamId: this.tagId.map(item => {return item.id}).join(','),
          pageNum,
          pageSize: 10,
          userName
        }

        const { code, data, msg } = await ReportApi.getPcTeamUser(params);
        if(code !== 200) return;

        this.total = data.totalCount;
        this.personnelList = this.personnelList.concat(data.baseUserDTOList);
      }catch(e) {
        console.log('taskSelect.vue/teamUser', e);
      }
    },
    // 人员搜索
    remoteMethod(query = '') {
      this.personSearchInfo.pageNum = 1;
      this.personSearchInfo.userName = query;
      this.personnelList = [];
      this.teamUser();
    },
    // 分页
    loadmore(){
      if(this.personnelList.length === this.total) return;
      
      this.personSearchInfo.pageNum++;
      this.teamUser();
    },
    searchChange(type) {
      this.Params()
      this.reportType && this.$track.commonFn.chartTrack(this.reportType, ({
        'time': 'REPORT_SEARCH_TIME',
        'taskType': 'REPORT_SEARCH_TASKTYPE',
        'user': 'REPORT_SEARCH_MANAGER_SEARCH'
      })[type], this.$track)
    },
    // 参数
    Params() {
      const {dataTime, department, tagId, personnel} = this
      this.$emit('taskParams', {
        taskTypeIds: department,
        userIds: personnel,
        tagIds: tagId.map(item => {return item.id}),
        timeStart: dataTime && this.reportType === 'task_success' ? dataTime[0] : undefined,
        timeEnd: dataTime && this.reportType === 'task_success' ? dataTime[1] : undefined,
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../system.scss';
</style>
<style lang="scss">
.event-select {
    .el-range-separator {
        width: 10%!important;
    }
}
</style>